package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"proj-man/cache"
	"proj-man/models"
	"strconv"
	"time"
)

func ProjAdd(c *gin.Context) {
	title := c.PostForm("title")
	addr := c.PostForm("addr")
	content := c.PostForm("content")
	if title == "" || addr == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不能为空",
		})
		return
	}

	data := models.Proj{

		Title:   title,
		Addr:    addr,
		Content: content,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "增加失败",
		})
		return
	}

	redis_key := "proj_id_" + strconv.Itoa(int(data.ID))
	var proj models.Proj
	models.DB.Where("id = ?", data.ID).First(&proj)
	jsonData, _ := json.Marshal(proj)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "增加成功",
	})
	return

}

func ProjList(c *gin.Context) {
	var proj []models.Proj

	redis_key := "proj_list_"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&proj)
		jsonData, _ := json.Marshal(proj)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &proj)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表展示成功",
		"data": proj,
	})
}

func Detail(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))

	var proj models.Proj
	err := models.DB.Where("id = ?", id).First(&proj).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查找失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "详情查找成功",
		"data": proj,
	})
	return
}

func ProjDel(c *gin.Context) {
	id := c.Query("id")

	var proj models.Proj
	err := models.DB.Where("id = ?", id).Delete(&proj).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}

	redis_key := "proj_del_" + id
	cache.Rdb.Del(cache.Ctx, redis_key)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
